<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-card class="search-card" shadow="never">
      <!-- 搜索操作 -->
      <template #header>
        <div class="card-header">
          <span>筛选条件</span>
          <el-button
            class="collapse-btn"
            type="text"
            @click="toggleSearch"
            :icon="showSearch ? 'ArrowDownBold' : 'ArrowUpBold'"
          >
            {{ showSearch ? "收起" : "展开" }}
          </el-button>
        </div>
      </template>

      <!-- 查询表单 -->
      <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item label="订单号" prop="orderCode">
          <el-input
            v-model="queryParams.orderCode"
            placeholder="请输入订单号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="顾客ID" prop="guestId">
          <el-input
            v-model="queryParams.guestId"
            placeholder="请输入顾客ID"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="订单类型" prop="orderType">
          <el-select
            v-model="queryParams.orderType"
            placeholder="请选择订单类型"
            clearable
          >
            <el-option
              v-for="dict in order_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="主状态" prop="masterStatus">
          <el-select
            v-model="queryParams.masterStatus"
            placeholder="请选择主状态"
            clearable
          >
            <el-option
              v-for="dict in master_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option
              v-for="dict in wdm_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 查询表单 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['ruoyi:order:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ruoyi:order:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ruoyi:order:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['ruoyi:order:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 列表表单 -->
    <el-table
      v-loading="loading"
      :data="orderList"
      border
      resizble
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="orderId" />
      <el-table-column
        label="订单号"
        min-width="250"
        align="center"
        prop="orderCode"
      />
      <el-table-column label="顾客ID" align="center" prop="guestId" />
      <el-table-column
        label="订单类型"
        align="center"
        min-width="100"
        prop="orderType"
      >
        <template #default="scope">
          <dict-tag :options="order_type" :value="scope.row.orderType" />
        </template>
      </el-table-column>
      <el-table-column label="总计金额" align="center" prop="totalAmount">
        <template #default="scope">{{ scope.row.totalAmount }}￥</template>
      </el-table-column>
      <el-table-column label="主状态" align="center" prop="masterStatus">
        <template #default="scope">
          <dict-tag :options="master_status" :value="scope.row.masterStatus" />
        </template>
      </el-table-column>
      <el-table-column
        label="下单时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="支付时间" align="center" prop="payTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.payTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="处理时间" align="center" prop="processTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.processTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="完成时间" align="center" prop="finishTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.finishTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="wdm_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="备注信息" align="center" prop="remark" />
      <!-- <el-table-column label="扩展数据" align="center" prop="orderExtra" /> -->
      <el-table-column
        label="操作"
        align="center"
        min-width="220"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            v-if="scope.row.masterStatus === '3'"
            link
            type="warning"
            icon="Check"
            @click="handleAudit(scope.row)"
            >审核
          </el-button>

          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ruoyi:order:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ruoyi:order:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="orderRef" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="订单号" prop="orderCode">
          <el-input v-model="form.orderCode" placeholder="请输入订单号" />
        </el-form-item> -->
        <el-form-item label="顾客ID" prop="guestId">
          <el-input v-model="form.guestId" placeholder="请输入顾客ID" />
        </el-form-item>
        <el-form-item label="订单类型" prop="orderType">
          <el-select v-model="form.orderType" placeholder="请选择订单类型">
            <el-option
              v-for="dict in order_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="总计金额" prop="totalAmount">
          <el-input v-model="form.totalAmount" placeholder="请输入总计金额" />
        </el-form-item>
        <el-form-item label="主状态" prop="masterStatus">
          <el-select v-model="form.masterStatus" placeholder="请选择主状态">
            <el-option
              v-for="dict in master_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="支付时间" prop="payTime">
          <el-date-picker
            clearable
            v-model="form.payTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择支付时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="处理时间" prop="processTime">
          <el-date-picker
            clearable
            v-model="form.processTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择处理时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="完成时间" prop="finishTime">
          <el-date-picker
            clearable
            v-model="form.finishTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择完成时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in wdm_status"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="删除标志" prop="delFlag">
          <el-radio-group v-model="form.delFlag">
            <el-radio
              v-for="dict in del_flag"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="扩展数据" prop="orderExtra">
          <el-input
            v-model="form.orderExtra"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 退款审核对话框 -->
    <el-dialog
      title="退款审核"
      v-model="auditDialogVisible"
      width="500px"
      append-to-body
    >
      <el-form :model="auditForm" ref="auditFormRef">
        <!-- 订单基本信息 -->
        <el-form-item label="订单编号">
          <span>{{ currentOrder.orderCode }}</span>
        </el-form-item>

        <!-- 退款信息 -->
        <el-form-item label="退款金额">
          <span
            >¥{{
              selectedRefundApplication?.totalAmount || currentOrder.totalAmount
            }}</span
          >
        </el-form-item>

        <el-form-item label="退款原因">
          <span>{{
            getRefundReasonLabel(selectedRefundApplication?.reason)
          }}</span>
        </el-form-item>

        <!-- 审核操作 -->
        <el-form-item label="审核结果" prop="auditStatus">
          <el-radio-group v-model="auditForm.auditStatus">
            <el-radio label="1">通过</el-radio>
            <el-radio label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          v-if="auditForm.auditStatus === '2'"
          label="拒绝原因"
          prop="auditReason"
          :rules="[{ required: true, message: '拒绝原因不能为空' }]"
        >
          <el-input
            v-model="auditForm.auditReason"
            type="textarea"
            placeholder="请输入拒绝原因"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAudit">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Order">
import { parseTime } from "@/utils/ruoyi";

import {
  listOrder,
  listOrderSummary,
  getOrder,
  delOrder,
  addOrder,
  updateOrder,
  auditRefundApplication,
} from "@/api/ruoyi/order";

import {
  listRefundInfo,
  getRefundInfo,
  delRefundInfo,
  addRefundInfo,
  updateRefundInfo,
  getActiveRefundsByOrderId,
  getLatestRefundByOrderId,
  getActiveRefundsByGoodsOrderId,
  getLatestRefundByGoodsOrderId,
} from "@/api/ruoyi/refundInfo";

const { proxy } = getCurrentInstance();
const {
  master_status,
  wdm_status,
  order_type,
  del_flag,
  refund_status,
  refund_reason,
} = proxy.useDict(
  "master_status",
  "wdm_status",
  "order_type",
  "del_flag",
  "refund_status",
  "refund_reason"
);

const orderList = ref([]);
const refundInfoList = ref([]);

const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderCode: null,
    guestId: null,
    orderType: null,
    masterStatus: null,
    status: null,

    // 退款信息
    paymentId: null,
    goodsOrderId: null,
    refundAmt: null,
    refundStatus: null,
    refundReason: null,
    refundTransId: null,
    refundTime: null,
    version: null,
    reason: null,
    refundCode: null,
  },
  rules: {
    // orderCode: [
    //   { required: true, message: "订单号不能为空", trigger: "blur" }
    // ],
    guestId: [{ required: true, message: "顾客ID不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

// 新增状态变量
const auditDialogVisible = ref(false);
const currentOrder = ref({});
const refundReason = ref("");
const auditForm = reactive({
  auditStatus: "",
  auditReason: "",
});

// 新增状态变量（添加到现有变量声明区域）
const refundApplications = ref([]); // 退款申请列表
const selectedRefundApplication = ref(null); // 当前选中的退款申请

// 审核按钮处理
const handleAudit = async (row) => {
  try {
    // 获取订单详情
    const orderRes = await getOrder(row.orderId);
    currentOrder.value = orderRes.data;

    // 使用正确的API获取退款信息
    const refundRes = await getActiveRefundsByGoodsOrderId(row.orderId);

    // 处理可能的返回结构
    let refundList = [];

    // 处理三种可能的返回结构
    if (Array.isArray(refundRes?.data)) {
      refundList = refundRes.data;
    } else if (
      refundRes?.data &&
      typeof refundRes.data === "object" &&
      !Array.isArray(refundRes.data)
    ) {
      refundList = [refundRes.data];
    } else if (Array.isArray(refundRes?.data?.rows)) {
      refundList = refundRes.data.rows;
    }

    refundApplications.value = refundList;

    // 设置默认选中项
    if (refundApplications.value.length > 0) {
      selectedRefundApplication.value = refundApplications.value[0];
      refundReason.value =
        selectedRefundApplication.value.reason || "用户申请退款";
    } else {
      selectedRefundApplication.value = null;
      refundReason.value = "未找到退款申请";
    }

    // 显示对话框
    auditForm.auditStatus = "";
    auditForm.auditReason = "";
    auditDialogVisible.value = true;
  } catch (error) {
    proxy.$modal.msgError("获取订单信息失败: " + error.message);
  }
};

// 提交审核
const submitAudit = () => {
  proxy.$refs.auditFormRef.validate(async (valid) => {
    if (valid) {
      try {
        // 安全检查：确保有退款申请
        if (refundApplications.value.length === 0) {
          throw new Error("该订单没有退款申请");
        }

        // 确保 selectedRefundApplication 有值（关键修复）
        if (
          !selectedRefundApplication.value &&
          refundApplications.value.length > 0
        ) {
          // 自动设置第一个退款申请
          selectedRefundApplication.value = refundApplications.value[0];
          console.warn(
            "自动选择了第一个退款申请",
            selectedRefundApplication.value
          );
        }

        // 确保有选中的退款申请
        if (!selectedRefundApplication.value) {
          throw new Error("未选择退款申请");
        }

        // 获取退款申请ID（确保是数字）
        const refundId = Number(selectedRefundApplication.value.refundId);
        if (isNaN(refundId)) {
          throw new Error("无效的退款申请ID");
        }

        // 调用审核API
        await auditRefundApplication(refundId, {
          auditStatus: auditForm.auditStatus,
          auditReason: auditForm.auditReason,
        });

        proxy.$modal.msgSuccess("审核提交成功");
        auditDialogVisible.value = false;
        getList(); // 刷新订单列表
      } catch (error) {
        proxy.$modal.msgError("审核失败: " + (error.message || error));
      }
    }
  });
};

// 新增：获取退款原因标签
function getRefundReasonLabel(reason) {
  if (!reason) return "无";

  // 安全检查：确保字典已加载
  if (!refund_reason.value || !Array.isArray(refund_reason.value)) {
    return reason; // 如果字典未加载，返回原始值
  }

  // 使用字典数据转换
  const item = refund_reason.value.find((d) => d.value === reason);
  return item ? item.label : reason;
}

// 新增：搜索区域折叠/展开
function toggleSearch() {
  showSearch.value = !showSearch.value;
}

/** 查询订单信息列表 */
// function getList() {
//   loading.value = true;
//   listOrder(queryParams.value).then((response) => {
//     // orderList.value = response.rows
//     // 过滤已删除数据（假设 delFlag 字段标识删除状态）
//     orderList.value = response.rows.filter((item) => item.delFlag !== "2");
//     total.value = response.total;
//     loading.value = false;
//   });
// }

/** 查询业务订单信息列表 */
function getList() {
  loading.value = true;
  listOrderSummary(queryParams.value).then((response) => {
    orderList.value = response.rows.filter((item) => item.delFlag !== "2");
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    orderId: null,
    orderCode: null,
    guestId: null,
    orderType: null,
    totalAmount: null,
    masterStatus: null,
    createTime: null,
    payTime: null,
    processTime: null,
    finishTime: null,
    status: null,
    delFlag: null,
    version: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null,
    orderExtra: null,
  };
  proxy.resetForm("orderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.orderId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加订单信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _orderId = row.orderId || ids.value;
  getOrder(_orderId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改订单信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["orderRef"].validate((valid) => {
    if (valid) {
      if (form.value.orderId != null) {
        updateOrder(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOrder(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _orderIds = row.orderId || ids.value;
  proxy.$modal
    .confirm('是否确认删除订单信息编号为"' + _orderIds + '"的数据项？')
    .then(function () {
      return delOrder(_orderIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "ruoyi/order/export",
    {
      ...queryParams.value,
    },
    `order_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>

<style scoped>
/* 搜索卡片样式 */
.search-card {
  /* margin-bottom: 16px; */
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  color: #303133;
}

.collapse-btn {
  padding: 0;
  font-size: 14px;
  color: #606266;
}
</style>
